// <copyright file="MenuLinkExtension.cs" company="Clever Software">
// Copyright (c) 2013, 2014 All Right Reserved, http://www.cleversoftware.by
//
// This source is subject to the Microsoft Permissive License.
// Please see the License.txt file for more information.
// All other rights reserved.
//
// THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY 
// KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// </copyright>
// <author>Clever Software</author>
// <email>info@cleversoftware.by</email>
// <date>2014-02-04</date> 
// <summary>CleverCMS source code</summary>

namespace CleverCMS.Core.Web.Extensions
{
    using System.Web.Mvc;
    using System.Linq;
    using System.Text;
    using System.Collections.Generic;
    using Cms.Data.Entities;

    public static class MenuLinkExtension
    {
        public static string BuildMenuLink(this UrlHelper urlHelper, CmsMenuItem item)
        {
            if (item.IsExternalUrl)
            {
                return item.NavigateUrl;
            }

            return urlHelper.Action("Content", "Home", new { name = item.Entry.Alias });
        }

        public static MvcHtmlString BuildMenu(this UrlHelper helper, ICollection<CmsMenuItem> menu)
        {
            return new MvcHtmlString(BuildStringMenu(helper, menu.Where(x => x.ParentId.HasValue == false).ToList()));
        }

        private static string BuildStringMenu(UrlHelper helper, ICollection<CmsMenuItem> menu)
        {
            var sb = new StringBuilder();
            if ((menu != null) && (menu.Count > 0))
            {
                foreach (var item in menu)
                {
                    bool hasSubItems = (item.MenuItems != null) && (item.MenuItems.Count > 0);
                    sb.Append(hasSubItems ? "<li class=\"menuparent\">" : "<li>" );

                    if (hasSubItems)
                    {
                        sb.Append("<span class=\"menuparent nolink\"><a href = \"" + (item.IsExternalUrl ? item.NavigateUrl : "/" + item.Entry.Alias) + "\">" + item.Title + "</a></span>");

                        sb.Append("<ul>");
                        sb.Append(BuildStringMenu(helper, item.MenuItems));
                        sb.Append("</ul>");
                    }
                    else 
                    {
                        sb.Append("<a class=\"subLink\" href = \"" + (item.IsExternalUrl ? item.NavigateUrl : "/" + item.Entry.Alias) + "\">" + item.Title + "</a>");
                    }

                    sb.Append("</li>");
                }
            }
            return (sb.ToString());
        }
    }
}